<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 会员设置
 */
namespace app\ais\controller\vip;
use app\ais\controller\Common;
use app\ais\model\AisVip;
use app\ais\model\AisCoupon;

class Coupon extends Common{

    public $mini_program   = []; 

    public function initialize() {
        parent::initialize();
        $this->assign('pathMaps',[['name'=>'会员组','url'=>url("vip.index/index")],['name'=>'优惠券','url'=>url("vip.coupon/index")]]);
    }

    /**
     * 列表
     */
    public function index(int $id){
        $condition = [];
        $vip = AisVip::where(['id' => $id,'member_miniapp_id' => $this->member_miniapp_id])->where($condition)->field('coupon_ids')->find();
        if(empty($vip)){
            $this->error('没有找到对应会员类型');
        }
        $view['lists']  = AisCoupon::where($this->mini_program)->whereIn('id',$vip->coupon_ids)->order('sort desc,id desc')->paginate(20,false,['query' => ['id' => $id]]);
        $view['id']     = $id;
        return view()->assign($view);
    }


    /**
     * 弹出选择优惠券
     */
    public function coupon(int $id){
        if(request()->isAjax()){
            $ids = $this->request->param('ids/s');
            if(empty($ids)){
                return json(['code'=>0,'msg'=>'请选择要关联的优惠券']);
            }
            $result = AisVip::editCoupon($id,ids($ids,true));
            if($result){
                return json(['code'=>302,'msg'=>'关联优惠券成功','data' =>[]]);
            }else{
                return json(['code'=>0,'msg'=>'关联优惠券失败']);
            }
        }else{
            $coupon      = AisVip::where($this->mini_program)->where(['id' => $id])->field('coupon_ids')->find();
            $coupon_ids  = [];
            if($coupon->coupon_ids){
                $coupon_ids = explode(',',$coupon->coupon_ids);
            }
            $keyword = $this->request->param('keyword');
            if(empty($keyword)){
                $sql = AisCoupon::where($this->mini_program);
            }else{
                $sql = AisCoupon::where($this->mini_program)->whereLike('name','%'.$keyword.'%'); 
            }
            $view['lists']   = $sql->whereNotIn('id',$coupon_ids)->where(['is_end' => 0])->order('id desc')->paginate(10,false,['query' => ['id' => $id,'keyword'=>$keyword]]); 
            $view['id']      = $id;
            $view['keyword'] = $keyword;
            return view()->assign($view);
        }
    }

   //删除
   public function delete(int $id,int $coupon_id){
        $result   = AisVip::where($this->mini_program)->where(['id' => $id])->find();
        if($result){
            $result->coupon_ids =  ids(array_values_unset($coupon_id,explode(',',$result->coupon_ids)));
            $result->save();
            return enjson(200);
        }
        return enjson(0);
    }
}